<?php
// 开启会话
session_start();

// 初始化停车位数据
if (!isset($_SESSION['parking_spaces'])) {
    // 假设有 5 个停车位，初始状态都为未占用
    $_SESSION['parking_spaces'] = array_fill(0, 5, false);
}

// 处理停车操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['park'])) {
    $selected_space = (int)$_POST['space'];
    if ($selected_space >= 0 && $selected_space < count($_SESSION['parking_spaces'])) {
        if ($_SESSION['parking_spaces'][$selected_space]) {
            $message = "该停车位已被占用，请选择其他车位。";
        } else {
            $_SESSION['parking_spaces'][$selected_space] = true;
            $message = "停车成功，你停在了第 ". ($selected_space + 1). " 个车位。";
        }
    } else {
        $message = "无效的停车位选择，请重新选择。";
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>停车位网页游戏</title>
</head>

<body>
    <h1>停车位网页游戏</h1>
    <h2>当前停车位状态</h2>
    <ul>
        <?php
        foreach ($_SESSION['parking_spaces'] as $index => $occupied) {
            $status = $occupied ? '已占用' : '空闲';
            echo "<li>第 ". ($index + 1). " 个车位: ". $status. "</li>";
        }
        ?>
    </ul>

    <?php if (isset($message)): ?>
        <p><?php echo $message; ?></p>
    <?php endif; ?>

    <h2>选择停车位停车</h2>
    <form method="post">
        <select name="space">
            <?php
            for ($i = 0; $i < count($_SESSION['parking_spaces']); $i++) {
                if (!$_SESSION['parking_spaces'][$i]) {
                    echo "<option value='$i'>第 ". ($i + 1). " 个车位</option>";
                }
            }
            ?>
        </select>
        <input type="submit" name="park" value="停车">
    </form>
</body>

</html>